<?php
namespace app\store\controller\order;

require 'vendor/autoload.php';

use app\store\controller\Controller;
use app\store\model\Order as OrderModel;
use app\store\model\Express as ExpressModel;
use PDO;
use PDOException;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

/**
 * 订单操作控制器
 * Class Operate
 * @package app\store\controller\order
 */
class Operate extends Controller
{
    /* @var OrderModel $model */
    private $model;

    /**
     * 构造方法
     * @throws \app\common\exception\BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new OrderModel;
    }

    /**
     * 订单导出
     * @param string $dataType
     * @throws \think\exception\DbException
     */
    public function export() 
    {
        //var_dump($this->request->param());exit;
        //return $this->model->exportList($dataType, $this->request->param());

        define('DBHOST', 'localhost');
        define('DBNAME', 'demo');//数据库名
        define('DBUSER', 'root');//账号
        define('DBPWD', 'root');//密码
        define('DBPREFIX', 'hw_');
        define('DBCHARSET', 'utf8');
        define('CONN', '');
        define('TIMEZONE', 'Asia/Shanghai');

        try{
            $db = new PDO('mysql:host='.DBHOST.';dbname='.DBNAME, DBUSER, DBPWD);
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $db->query('SET NAMES utf8;');
        }catch(PDOException  $e ){
            echo '{"result":"failed", "msg":"连接数据库失败！"}';
            exit;
        }
        $spreadsheet = new Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        $worksheet->setTitle('学生成绩表');

        //表头
        //设置单元格内容
        //使用数字单元格坐标设置单元格值。
        $worksheet->setCellValueByColumnAndRow(1, 1, '学生成绩表');
        $worksheet->setCellValueByColumnAndRow(1, 2, '姓名');
            $worksheet->setCellValueByColumnAndRow(2, 2, '语文');
            $worksheet->setCellValueByColumnAndRow(3, 2, '数学');
            $worksheet->setCellValueByColumnAndRow(4, 2, '外语');
            $worksheet->setCellValueByColumnAndRow(5, 2, '总分');

            //合并单元格
            $worksheet->mergeCells('A1:E1');

            $styleArray = [
                'font' => [
                    'bold' => true
                ],
                'alignment' => [
                    'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                ],
            ];
            //设置单元格样式
            $worksheet->getStyle('A1')->applyFromArray($styleArray)->getFont()->setSize(28);

            $worksheet->getStyle('A2:E2')->applyFromArray($styleArray)->getFont()->setSize(14);
            //$worksheet->getStyle('A2:D2')->getFont()->setSize(14);


            //读取数据
            $sql = "SELECT id,name,chinese,maths,english FROM `t_student`";
            $stmt = $db->query($sql);
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
            $len = count($rows);
            $j = 0;
            for ($i=0; $i < $len; $i++) { 
                $j = $i + 3;
                $worksheet->setCellValueByColumnAndRow(1, $j, $rows[$i]['name']);
                $worksheet->setCellValueByColumnAndRow(2, $j, $rows[$i]['chinese']);
                $worksheet->setCellValueByColumnAndRow(3, $j, $rows[$i]['maths']);
                $worksheet->setCellValueByColumnAndRow(4, $j, $rows[$i]['english']);
                $worksheet->setCellValueByColumnAndRow(5, $j, $rows[$i]['chinese'] + $rows[$i]['maths'] + $rows[$i]['english']);
            }


            $styleArrayBody = [
                'borders' => [
                    'allBorders' => [
                        'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
                        'color' => ['argb' => '666666'],
                    ],
                ],
                'alignment' => [
                    'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                ],
            ];
            $total_rows = $len + 2;
            //添加所有边框/居中
            $worksheet->getStyle('A1:E'.$total_rows)->applyFromArray($styleArrayBody);


        // 下载
        $filename = '成绩表.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');
    }

    /**
     * 批量发货
     * @return array|bool|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function batchDelivery()
    {
        if (!$this->request->isAjax()) {
            return $this->fetch('batchDelivery', [
                'express_list' => ExpressModel::getAll()
            ]);
        }
        if ($this->model->batchDelivery($this->postData('order'))) {
            return $this->renderSuccess('发货成功');
        }
        return $this->renderError($this->model->getError() ?: '发货失败');
    }

    /**
     * 批量发货模板
     */
    public function deliveryTpl()
    {
        return $this->model->deliveryTpl();
    }

    /**
     * 审核：用户取消订单
     * @param $order_id
     * @return array|bool
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function confirmCancel($order_id)
    {
        $model = OrderModel::detail($order_id);
        if ($model->confirmCancel($this->postData('order'))) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError($model->getError() ?: '操作失败');
    }

    /**
     * 门店自提核销
     * @param $order_id
     * @return array|bool
     * @throws \think\exception\DbException
     */
    public function extract($order_id)
    {
        $model = OrderModel::detail($order_id);
        $data = $this->postData('order');
        if ($model->verificationOrder($data['extract_clerk_id'])) {
            return $this->renderSuccess('核销成功');
        }
        return $this->renderError($model->getError() ?: '核销失败');
    }

}
